package com.cssl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cssl.api.ApiUserLabel;
import com.cssl.dto.CreateOrderDTO;
import com.cssl.dto.DeplaneOrderDTO;
import com.cssl.dto.OrderStatisticsDTO;
import com.cssl.dto.ProductOrderDTO;
import com.cssl.entity.*;
import com.cssl.exception.BusinessException;
import com.cssl.message.IMessage;
import com.cssl.service.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@RefreshScope
@RestController
@Tag(name = "订单控制器")
public class OrderController {
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class); // 日志记录器

    @Autowired
    private ApiUserLabel userApi;
    @Autowired
    private OrderService os; //网费订单表
    @Autowired
    private IMessage message; //消息队列接口
    @Autowired
    private ProductOrderService pos; //商品订单表
    @Autowired
    private ProductDetailsService pds; //商品订单详情
    @Autowired
    private EquipmentRepairService erps; //维修订单
    @Autowired
    private TopUpService tus; //用户充值表


    /**
     * 查询所有网费订单
     * @return
     */
    @PostMapping("/findOrder")
    public List<OrderForm> findOrder(){
        return os.list();
    }


    /**
     * 创建网费订单 （上机）
     * 
     * @return
     */
    @PostMapping("/createInternetOrder")
    public String createInternetOrder(CreateOrderDTO coDto){
        try{
            return os.createOrder(coDto);
        }catch (Exception e){
            return "订单创建失败";
        }
    }

    /**
     * 创建商品订单
     * @param pod
     * @return
     */
    @PostMapping("/createProductOrder")
    public String createProductOrder(ProductOrderDTO pod){
        try {
            Map<Integer,Integer> map = pos.createOrder(pod); // 调用订单服务，创建订单
            //发送消息给商品服务扣减库存
            message.reduceInventory(map);
            return "订单创建成功"; // 如果成功，返回成功信息
        } catch (BusinessException e) {
            logger.error("订单创建失败：{}", e.getMessage(), e); // 记录错误日志，包含异常信息
            return "订单创建失败";
        }
    }

    /**
     * 用户下机
     * @param doDTO
     * @return
     */
    @PostMapping("/deplane")
    public String deplane(DeplaneOrderDTO doDTO){
        //修改订单 计算网费 扣减余额
        return os.deplane(doDTO);
    }

    /**
     * 订单数据统计
     * @return
     */
    @PostMapping("/orderDataStatistics")
    public OrderStatisticsDTO orderDataStatistics(){
        OrderStatisticsDTO orderStat = new OrderStatisticsDTO(
                os.computerNum(),
                os.todayIncome(),
                os.findAverageTime(),
                tus.rechargeToday(),
                os.totalTime(),
                os.computerNum_yd(),
                os.todayIncome_yd(),
                os.findAverageTime_yd(),
                tus.rechargeToday_yd(),
                os.totalTime_yd()
        );
        return orderStat;
    }

    /**
     * 修改订单状态
     * @param po_id
     * @return
     */
    @PostMapping("/updateStatus")
    public String updateStatus(@RequestParam("po_id") String po_id){
        //修改状态为已付款
        if(pos.updateById(new ProductOrder(po_id,1)))
            return "修改订单状态成功";
        else
            return "修改订单状态失败";
    }

    /**
     * 根据座位id删除对应的订单
     * @return
     */
    @PostMapping("/deleteOrderEid")
    public String deleteOrderEid(@RequestBody List<Integer> eq_ids){
        try {
            //删除维修订单
            erps.getBaseMapper().delete(
                    new QueryWrapper<EquipmentRepair>().in("eq_id", eq_ids));
            //删除上机订单
            os.getBaseMapper().delete(
                    new QueryWrapper<OrderForm>().in("eq_id", eq_ids)
            );
            //删除商品详情订单
            //查询指定座位下的订单信息的主键
            List<String> list_poId = pos.getBaseMapper().selectObjs(
                    new QueryWrapper<ProductOrder>().in("eq_id", eq_ids));
            //把所有商品订单下的详情订单信息删除
            pds.getBaseMapper().delete(
                    new QueryWrapper<ProductDetails>().in("po_id", list_poId)
            );
            //删除所有商品订单
            pos.getBaseMapper().deleteByIds(list_poId);
            return "订单删除成功"; // 如果成功，返回成功信息
        } catch (Exception e) {
            return "订单删除失败";
        }
    }
}
